//
//  XLHistoryViewController.m
//  History
//
//  Created by 于鹏 on 2017/8/10.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "XLHistoryViewController.h"

#import "XLHistoryCell.h"
#import "XLHistoryEditHeaderView.h"
#import "XLHistoryModel.h"
#import "XLSearchBar.h"
#import "YYModel.h"
#import "MJRefresh.h"
//#import <XLBaseModule/XLSearchBar.h>

#define kXLHistoryHeaderHeight 40
#define kXLHistoryHeaderSize CGRectMake(0, 0, KScreenWidth, kXLHistoryHeaderHeight)
typedef NS_ENUM(NSInteger, XLHistoryHeaderType) {
    XLHistoryHeaderSearch = 0,
    XLHistoryHeaderEdit = 1
};
@interface XLHistoryViewController ()<UITableViewDelegate,UITableViewDataSource,XLSearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)XLSearchBar *searchBar;
@property (nonatomic,strong)XLHistoryEditHeaderView *editView;
@property (nonatomic,assign)XLHistoryHeaderType headerType;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSMutableArray *selectArr;
@property (nonatomic, assign, getter=isSearch)BOOL search;//是否在搜索
@property (nonatomic, strong)NSMutableArray *searchArr;

@end

@implementation XLHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    UINib *nib = [[Lothar shared]current_cellNib];
//    [self.tableView registerNib:nib forCellReuseIdentifier:[[Lothar shared]current_cellIdentifier]];
    self.title = @"历史会诊";
    [self.tableView registerNib:[XLHistoryCell xl_nib] forCellReuseIdentifier:[XLHistoryCell identifier]];
}

#pragma mark - override

- (void)initData {
//    [super initData];
//    for (int i = 0; i< 20; i++) {
//        XLHistoryModel *model = [[XLHistoryModel alloc]init];
//        model.select = NO;
//        [self.dataArr addObject:model];
//    }
//    [self dismissHUD];
//    [self.tableView reloadData];
    
    
}

- (void)get_initData
{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@"0" forKey:@"Start"];
    [parameters setValue:@"0" forKey:@"Length"];
    [parameters setValue:UserInfo.userID forKey:@"doctorID"];
    [parameters setValue:UserInfo.tokenCode forKey:@"token"];
    [XLHTTPRequest ETM_getHistoryListWithParameters:parameters responseCache:nil success:^(id responseObject) {
        
        if (self.dataArr.count > 0) {
            [self.dataArr removeAllObjects];
        }
        
        for (NSDictionary *dic in responseObject[@"data"]) {
            XLHistoryModel *model = [XLHistoryModel yy_modelWithJSON:dic];
            model.select = NO;
            [self.dataArr addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error, NSString *info) {
        [self.tableView.mj_header endRefreshing];
        if (error == nil) {
            [self exitLogin:info];
        }
    }];
}

- (void)initInterface {
    self.tableView.backgroundColor = kBackground_color;
    self.headerType = XLHistoryHeaderSearch;
    self.tableView.allowsSelection = NO;//设置没有编辑时不能点击
    self.tableView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self get_initData];
    }];
    [self.tableView.mj_header beginRefreshing];

    self.tableView.tableFooterView = [self footerView];
//    [self setUpNavItem];
    
    XLWeakSelf(self);
    [self.searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        XLLog(@"searchText:%@",searchText);
    }];
    
    self.editView.editBlock = ^(UIButton *sender, XLHistoryHeaderEditType editType) {
        switch (editType) {
            case XLHistoryEditTypeSelectAll:{
                [weakself selectAllAction:sender];
                break;
            }
            case XLHistoryEditTypeCollect:{
                
                break;
            }
            case XLHistoryEditTypeDelete:{
                [weakself deleteAction:sender];
                break;
            }
            default:
                break;
        }
    };
    
}

- (void)setUpNavItem {
    UIButton *editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    editBtn.frame = CGRectMake(0, 0, 44, 44);
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"完成" forState:UIControlStateSelected];
    [editBtn addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]initWithCustomView:editBtn];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
}

- (UIView *)footerView {
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    UILabel *label = [[UILabel alloc]initWithFrame:footerView.frame];
    label.font = XLLabelFontNormal;
    label.textColor = kXLTextColor_GRAY;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"暂无更多历史会诊";
    [footerView addSubview:label];
    
    return footerView;
}
#pragma mark - UITableViewDataSource & Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isSearch ? self.searchArr.count :self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewCell *cell = [[Lothar shared]current_tableViewCellWithIdentifier:[[Lothar shared]current_cellIdentifier] tableView:tableView indexPath:indexPath];
    XLHistoryCell *cell = (XLHistoryCell *)[XLHistoryCell cellWithIdentifier:[XLHistoryCell identifier] tableView:tableView indexPath:indexPath];
    XLHistoryModel *model = self.isSearch ? self.searchArr[indexPath.row] : self.dataArr[indexPath.row];
    if (model.isSelected) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    } else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
    if (self.dataArr.count) {
        cell.model = self.dataArr[indexPath.row];
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XLHistoryModel *model = self.dataArr[indexPath.row];
    model.select = YES;
    if (![self.selectArr containsObject:model]) {
        [self.selectArr addObject:model];
    }

    XLLog(@"选中");
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    XLHistoryModel *model = self.dataArr[indexPath.row];
    model.select = NO;
    if ([self.selectArr containsObject:model]) {
        [self.selectArr removeObject:model];
    }
    XLLog(@"取消选中");

}

#pragma mark - Action 

- (void)editAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    self.headerType = sender.isSelected;
    [self.tableView setEditing:sender.selected animated:YES];
    if (!sender.isSelected) {
        self.editView.selectAllBtnIsSelect = NO;
        [self.selectArr removeAllObjects];
        for (XLHistoryModel *model in self.dataArr) {
            model.select = NO;
        }
        [self.tableView reloadData];
    }else {
        self.search = NO;
        [self.tableView reloadData];
    }
}

//全选
- (void)selectAllAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        NSArray<NSIndexPath *> *arr = self.tableView.indexPathsForVisibleRows;
        //全选
        for (XLHistoryModel *model in self.dataArr) {
            model.select = YES;
        }
        [self.selectArr removeAllObjects];
        [self.selectArr addObjectsFromArray:self.dataArr];
//        [self.tableView reloadData];
        for (NSIndexPath *indexPath in arr) {
            [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
    } else {
        //取消全选
        [self.selectArr removeAllObjects];
        for (XLHistoryModel *model in self.dataArr) {
            model.select = NO;
        }
        [self.tableView reloadData];
    }
}

//收藏
- (void)collect {
    if (self.selectArr.count == 0) {
        return;
    }
}

//删除
- (void)deleteAction:(UIButton *)sender {
    if (self.selectArr.count == 0) {
        return;
    }
    NSMutableArray<NSIndexPath *> *indexArr = [NSMutableArray array];
    for (int i = 0; i < self.selectArr.count; i++) {
        NSInteger index = [self.dataArr indexOfObject:self.selectArr[i]];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [indexArr addObject:indexPath];
    }
    
    [self.selectArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([self.dataArr containsObject:obj]) {
            [self.dataArr removeObject:obj];
        }
    }];
    
    [self.selectArr removeAllObjects];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView deleteRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationNone];
    });
    
    
}

#pragma mark - Setter
- (void)setHeaderType:(XLHistoryHeaderType)headerType {
    _headerType = headerType;
    switch (headerType) {
        case XLHistoryHeaderSearch:
            self.tableView.tableHeaderView = self.searchBar;
            break;
        case XLHistoryHeaderEdit:
            self.tableView.tableHeaderView = self.editView;
            break;
            
        default:
            break;
    }
}

#pragma mark - XLSearchBarDelegate

- (void)xl_searchBar:(XLSearchBar *)searchBar searchText:(NSString *)searchText {
    self.search = YES;
    if (self.searchArr.count > 0) {
        [self.searchArr removeAllObjects];
    }
    for (XLHistoryModel *model in self.dataArr) {
        if ([model.PatientName containsString:searchText] || [model.firstAidType containsString:searchText] || [model.doctorName containsString:searchText] || [model.hospital containsString:searchText]) {
            [self.searchArr addObject:model];
        }
    }
    [self.tableView reloadData];
}

- (void)xl_cancleSearch:(XLSearchBar *)searchBar {
    self.search = NO;
    [self.tableView reloadData];
    
    
}

#pragma mark - Getter
- (XLSearchBar *)searchBar {
    if (!_searchBar) {
//        _searchBar = [[XLSearchBar alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, kXLHistoryHeaderHeight)];
        _searchBar = [[XLSearchBar alloc]initWithFrame:kXLHistoryHeaderSize];
        _searchBar.searchDelegate = self;
    }
    return _searchBar;
}

- (XLHistoryEditHeaderView *)editView {
    if (!_editView) {
        _editView = [XLHistoryEditHeaderView creatEditView];
        _editView.frame = kXLHistoryHeaderSize;
    }
    return _editView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [NSMutableArray array];
    }
    return _selectArr;
}

- (NSMutableArray *)searchArr {
    if (!_searchArr) {
        _searchArr = [NSMutableArray array];
    }
    return _searchArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
